package indi.zhifa.study2025.test.rabbitmq.common.utils;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import indi.zhifa.study2025.test.rabbitmq.common.config.RabbitMqConfigNw;
import lombok.SneakyThrows;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;

public class NWRabbitUtils {
    private static ConnectionFactory mConnectionFactory;
    static {
        Yaml yaml = new Yaml();
        try (InputStream inputStream = NWRabbitUtils.class.getClassLoader().getResourceAsStream("rabbitmq.yml")) {
            if (inputStream == null) {
                throw new IllegalArgumentException("File not found: application.yml");
            }
            RabbitMqConfigNw mqConfig = yaml.loadAs(inputStream, RabbitMqConfigNw.class);
            mConnectionFactory = new ConnectionFactory();
            mConnectionFactory.setHost(mqConfig.getHost());
            mConnectionFactory.setPort(mqConfig.getPort());
            mConnectionFactory.setUsername(mqConfig.getUserName());
            mConnectionFactory.setPassword(mqConfig.getPasswd());
            mConnectionFactory.setVirtualHost(mqConfig.getVirtualHost());
            mConnectionFactory.setConnectionTimeout(1500);

        } catch (Exception e) {
            throw new RuntimeException("Failed to load YAML file", e);
        }
    }
    @SneakyThrows
    public static Connection getConnection() {
        try{
            Connection connection = mConnectionFactory.newConnection();
            return connection;
        }catch (Exception e) {
            System.out.println("获取连接时出现错误,"+e.getMessage());
        }
        return null;
    }
}
